package jdbc03;

import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
*   测试工具类
* */
public class JDBCUtilsDemo {
    @Test
    public void testSelect() throws SQLException {
        //1.通过工具类获取连接
        Connection conn = JDBCUtils.getConnection();
        //2.通过PreparedStatement预编译SQL并执行
        PreparedStatement ps = conn.prepareStatement("SELECT * FROM product WHERE cid = ?");
        //3.设置占位符参数值
        ps.setInt(1, 2);
        //4.执行SQL
        ResultSet resultSet = ps.executeQuery();
        //5.遍历结果集
        while (resultSet.next()) {
            System.out.println(resultSet.getString("pname") + " "
                    + resultSet.getDouble("price") + " "
                    + resultSet.getInt("cid"));
        }
        //6.释放资源
        JDBCUtils.release(conn, ps, resultSet);
    }

    @Test
    public void testUpdate() throws Exception {
        //1.通过工具类获取连接
        Connection conn = JDBCUtils.getConnection();
        //2.通过PreparedStatement预编译SQL并执行
        PreparedStatement ps = conn.prepareStatement("UPDATE product SET cid = ? WHERE pid = ?");

        //3.设置占位符参数值
        ps.setInt(1, 2);
        ps.setInt(2, 12);
        //4.执行SQL
        System.out.println(ps.executeUpdate());

        //5.释放资源
        JDBCUtils.release(conn, ps, null);

    }
}
